package sc.test.spring.quartz.config;

import java.util.concurrent.atomic.AtomicInteger;

import org.joda.time.DateTime;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.StatefulJob;
import org.springframework.scheduling.quartz.QuartzJobBean;

/**
 * 1. 每次执行的Job都是新实例，所以只有static可以共享
 * 2. StatefulJob为了保证任务不同时执行，在执行期间不会累积
 * @author zhoucong
 * time : 2013-2-27 下午1:58:26
 */
public class ExampleJob extends QuartzJobBean implements StatefulJob {

    public static AtomicInteger count = new AtomicInteger();
    public static int sleepSeconds = 10;

    String param;

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        int ct = count.incrementAndGet();
        System.out.println(ct + ", " + DateTime.now() + ", param " + param + ", sleep " + sleepSeconds + "s");
        try {
            Thread.sleep(sleepSeconds * 1000);
            if (sleepSeconds > 0) {
                sleepSeconds -= 2;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(ct + ", " + DateTime.now() + ", param " + param + ", wake up");
    }

    public void setParam(String param) {
        this.param = param;
    }

}
